package com.ijiangtao.studevtech.demo.csv.day.DT20170501.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;

import com.ijiangtao.studevtech.demo.csv.day.DT20170501.model.UserBean;

public class CsvUtil{

	//slf4j
	private static Logger LOGGER = LoggerFactory.getLogger(CsvUtil.class);
	
	
	/**
	 *  根据路径和文件名读取CSV文件，并将文件内容存在List中返回
	 * @param path csv文件所在的路径
	 * @param fileName 要读取的csv文件的文件名（可以为多个）
	 * @param cellProcessor Cell处理器
	 * @param clazz  此csv文件映射的对象
	 * @return
	 */
	public static List<CsvBean> CsvReader(String path,String[] fileName,CellProcessor[] cellProcessor,Class<? extends CsvBean> clazz){
		List<CsvBean>  beans=new ArrayList<>();
		
		ICsvBeanReader inFile = null;// Interface for CSV readers reading into objects/beans.
		FileReader fr=null;
		try {
			File f = new File(path);
			String absolutePath = f.getAbsolutePath();// 获取文件所在的绝对路径
			LOGGER.info("csv CsvReader absolutePat="+absolutePath);
			for (String name : fileName) {
				LOGGER.info("csv CsvReader fileName="+name);
				fr=new FileReader(absolutePath + "\\"+name+".csv");
				inFile = new CsvBeanReader(fr, CsvPreference.EXCEL_PREFERENCE);
				final String[] header = inFile.getHeader(true);
				CsvBean bean=null;
				while ((bean = inFile.read(clazz, header,cellProcessor)) != null) {
					beans.add(bean);
					LOGGER.info("----------------------------- csv CsvReader bean="+bean);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("!!!!!!!!!!!!!!!!!!!!!!!! 写入csv文件失败");
		} finally {
			//关闭流以及相关的所有流
			if (inFile != null) {
				try {
					inFile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return beans;
	}
	
	
	/**
	 * 根据路径名和列名输出指定对象到csv文件
	 * @param path csv文件路径
	 * @param header csv文件的列名
	 * @param cellProcessor Cell处理器
	 * @param beans 要输出到文件内的对象
	 */
	public static void CsvWriter(String path ,String header[],CellProcessor[] cellProcessor,List<CsvBean> beans){
		ICsvBeanWriter writer = null;
		File file = null;
		FileOutputStream fos=null;
		OutputStreamWriter osw=null;
		try {
			
			File f = new File(path);
			if(!f.exists()){
				f.mkdirs();
			}
			String absolutePath = f.getAbsolutePath();
			
			//生成CSV文件名：年月日时分秒.csv
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
			String dateTime = format.format(new Date());
			file = new File(absolutePath + "\\" + dateTime + ".csv");
			file.createNewFile();
			fos=new FileOutputStream(file);	
			osw=new OutputStreamWriter(fos,"UTF-8");
			writer = new CsvBeanWriter(osw,CsvPreference.EXCEL_PREFERENCE);

			// 输出头部
			writer.writeHeader(header);
			//依次输出每条记录
			for (CsvBean csvBean : beans) {
				writer.write(csvBean, header, cellProcessor);
			}

		} catch (Exception e) {	
			//关闭流
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException ew) {
					ew.printStackTrace();
				}
			}
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if(osw!=null){
				try {
					osw.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			//发生异常则删除生成的文件
			if(file!=null){
				file.delete();
			}
			e.printStackTrace();
			LOGGER.error("!!!!!!!!!!!!!!!!!!!!!!!! 读取csv文件失败");
		} finally {
			//关闭流
			if (writer != null) {
				try {
					/*
					Closes this stream and releases any system resources associated with it. 
					If the stream is already closed then invoking this method has no effect. 
					 */
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
